<template>
  <a-modal
    :closable="false"
    :confirm-loading="loading"
    :mask-closable="maskCloseable"
    :cancel-button-props="{ props: { disabled: buttonState } }"
    :ok-button-props="{ props: { disabled: buttonState } }"
    :okText="okText"
    :title="formTitle"
    :visible="open"
    :width="780"
    @cancel="onClose"
    @ok="onOk"
  >
    <!-- 步骤条 -->
    <a-steps :current="current">
      <a-step v-for="item in steps" :key="item.title" :title="item.title" />
    </a-steps>

    <!-- 步骤条内容 -->
    <div class="steps-content">
      <a-form-model ref="form" :label-col="labelCol" :model="form" :rules="rules" :wrapper-col="wrapperCol">
        <div v-if="current === 0">
          <a-form-model-item
            :colon="false"
            label="案例名称"
            prop="caseName">
            <a-input v-model="form.caseName" placeholder="请输入案例名称" />
          </a-form-model-item>
          <a-form-model-item
            :colon="false"
            help="案例类型不同产生的案例数据也不同"
            label="案例类型"
            prop="caseType">
            <a-select v-model="form.caseType" allow-clear placeholder="请选择案例类型" style="width: 100%">
              <a-select-option v-for="(d, index) in hotelTypeOptions" :key="index" :value="d.dictValue">
                {{ d.dictLabel }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
            :colon="false"
            label="初始金额"
            prop="initAmount">
            <a-input-number
              v-model="form.initAmount"
              :min="0"
              placeholder="请输入初始资金"
              style="width: 100%" />
          </a-form-model-item>
          <a-form-model-item
            :colon="false"
            label="回合总数"
            prop="round">
            <a-input-number
              v-model="form.round"
              :min="0"
              placeholder="请输入回合总数"
              style="width: 100%" />
          </a-form-model-item>
          <a-form-model-item :colon="false" label="案例描述" prop="caseDescribe">
            <a-input
              v-model="form.caseDescribe"
              :auto-size="{ minRows: 5, maxRows: 5 }"
              placeholder="请输入内容"
              type="textarea"
            />
          </a-form-model-item>
        </div>
        <div v-if="current === 1">
          <a-form-model-item
            :colon="false"
            label="城市设置"
            prop="cityId">
            <a-select v-model="form.cityId" allow-clear placeholder="请选择城市" style="width: 100%">
              <a-select-option v-for="(d, index) in cityOptions" :key="index" :value="d.cityId">
                {{ d.cityName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
            :colon="false"
            label="布局模式"
            help="选择系统推荐，将会根据案例类型匹配最佳布局"
            prop="layoutModel">
            <a-select v-model="form.layoutModel" default-value="recommended" @change="handleLayoutModel">
              <a-select-option value="recommended">
                使用系统推荐
              </a-select-option>
              <a-select-option value="optional">
                自选功能布局
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item v-if="layoutShow" :colon="false" label="布局设置" prop="layoutIds">
            <a-select
              v-model="form.layoutIds"
              allow-clear
              mode="multiple"
              placeholder="请选择布局"
              style="width: 100%">
              <a-select-opt-group v-for="d in layoutTypeOptions" :key="d.dictValue" :label="d.dictLabel">
                <a-select-option
                  v-for="(l, index) in layoutOptions"
                  v-if="l.layoutType === d.dictValue"
                  :key="index"
                  :value="l.layoutId">
                  {{ l.layoutName }}
                </a-select-option>
              </a-select-opt-group>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
            :colon="false"
            label="人员模式"
            help="选择系统推荐，将会根据案例类型匹配最佳布局"
            prop="personnelModel">
            <a-select v-model="form.personnelModel" default-value="recommended" @change="handlePersonnelModel">
              <a-select-option value="recommended">
                使用系统推荐
              </a-select-option>
              <a-select-option value="optional">
                自选人员配置
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item v-if="deptShow" :colon="false" label="部门设置" prop="depts">
            <a-tree-select
              v-model="form.depts"
              style="width: 100%"
              :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
              :tree-data="deptOptions"
              treeCheckable
              treeCheckStrictly
              placeholder="请选择"
              :replaceFields="{children:'children', title:'deptName', key:'deptId', value: 'deptId' }"
              @change="deptChange"
            >
            </a-tree-select>
          </a-form-model-item>
          <a-form-model-item v-if="postShow" :colon="false" label="岗位设置" prop="postIds">
            <a-select
              v-model="form.postIds"
              allow-clear
              mode="multiple"
              placeholder="请选择岗位"
              style="width: 100%">
              <a-select-opt-group v-for="d in deptGroupList" :key="d.value" :label="d.label">
                <a-select-option
                  v-for="(l, index) in postOptions"
                  v-if="l.deptId === d.value"
                  :key="index"
                  :value="l.postId">
                  {{ l.postName }}
                </a-select-option>
              </a-select-opt-group>
            </a-select>
          </a-form-model-item>
        </div>
        <div v-if="current === 2" align="center" style="margin-top: 50px">
          <a-progress
            :status="progressStatus"
            :percent="progress"
            :stroke-color="{
              '0%': '#108ee9',
              '100%': '#87d068',
            }"
            :width="200"
            type="circle"
          />
          <br>
          <br>
          <span>{{ progressMsg }}</span>
        </div>
        <div v-if="current === 3">
          <a-result
            v-if="resultShow"
            :sub-title="'您的案例' + form.caseName + '创建成功'"
            status="success"
            title="操作成功"
          >
          </a-result>
          <a-result
            v-else
            :sub-title="'您的案例' + form.caseName + '创建失败,请检查您的案例配置是否正确！'"
            status="error"
            title="操作失败"
          >
          </a-result>
        </div>
      </a-form-model>
    </div>

    <!-- websocket -->
    <web-socket
      ref="webSocket"
      @close="webSocketClose"
      @error="webSocketError"
      @message="webSocketMessage"
      @success="webSocketSuccess" />
  </a-modal>
</template>

<script>
import { getCase, addCase, updateCase } from '@/api/instance/case'
import { listLayout } from '@/api/platform/layout'
import { listDept } from '@/api/platform/dept'
import { listPostByDeptIds } from '@/api/platform/post'
import WebSocket from '@/components/WebSocket/WebSocket'

export default {
  name: 'CreateForm',
  props: {
    hotelTypeOptions: {
      type: Array,
      required: true
    },
    cityOptions: {
      type: Array,
      required: true
    }
  },
  components: {
    WebSocket
  },
  data () {
    return {
      // 部门列表
      depts: [],
      // 错误原因
      webMsg: undefined,
      // 结果页
      resultShow: true,
      // 部门是否可见
      deptShow: false,
      // 岗位是否可见
      postShow: false,
      // 布局是否可见
      layoutShow: false,
      // 按钮是否可点击
      buttonState: false,
      // 进度条
      progress: 0,
      // 执行内容
      progressMsg: '数据执行中...',
      // 进度条状态
      progressStatus: 'normal',
      // 布局类型字典
      layoutTypeOptions: [],
      // 布局列表
      layoutOptions: [],
      // 部门列表
      deptOptions: [],
      // 岗位分组列表
      deptGroupList: [],
      // 岗位列表
      postOptions: [],
      // 步骤条下标
      current: 0,
      // 步骤条标题
      steps: [
        {
          title: '基本信息'
        },
        {
          title: '配置信息'
        },
        {
          title: '创建案例'
        },
        {
          title: '完成'
        }
      ],
      // 确认按钮
      okText: '下一步',
      // 是否加载
      loading: false,
      // form表单
      labelCol: { span: 4 },
      wrapperCol: { span: 18 },
      // 表单名称
      formTitle: '',
      // 表单参数
      form: {
        caseId: undefined,
        userId: undefined,
        deptId: undefined,
        caseName: undefined,
        caseDescribe: undefined,
        caseType: undefined,
        initAmount: undefined,
        electricity: undefined,
        water: undefined,
        round: undefined,
        city: undefined,
        layoutIds: [],
        remark: undefined,
        layoutModel: 'recommended',
        personnelModel: 'recommended',
        deptIds: [],
        depts: [],
        postIds: []
      },
      // 是否打开弹窗
      open: false,
      // 点击蒙层是否允许关闭
      maskCloseable: false,
      rules: {
        caseName: [
          { required: true, message: '案例名称不能为空', trigger: 'change' }
        ],
        caseType: [
          { required: true, message: '案例类型不能为空', trigger: 'change' }
        ],
        initAmount: [
          { required: true, message: '初始金额不能为空', trigger: 'change' }
        ],
        round: [
          { required: true, message: '回合总数不能为空', trigger: 'change' }
        ],
        caseDescribe: [
          { required: true, message: '案例描述不能为空', trigger: 'change' }
        ],
        cityId: [
          { required: true, message: '案例城市不能为空', trigger: 'change' }
        ],
        layoutModel: [
          { required: true, message: '布局模式不能为空', trigger: 'change' }
        ],
        layoutIds: [
          { required: true, message: '布局设置不能为空', trigger: 'change' }
        ],
        personnelModel: [
          { required: true, message: '人员模式不能为空', trigger: 'change' }
        ],
        depts: [
          { required: true, message: '部门设置不能为空', trigger: 'change' }
        ],
        postIds: [
          { required: true, message: '岗位设置不能为空', trigger: 'change' }
        ]
      }
    }
  },
  filters: {},
  created () {
    // 酒店类型字典
    this.getDicts('layout_type').then(response => {
      this.layoutTypeOptions = response.data
    })
    // 部门列表
    this.getList()
    // 酒店布局列表
    this.getLayoutList()
  },
  computed: {},
  watch: {},
  mounted () {
  },
  methods: {
    /** 查询部门设置列表 */
    getList () {
      listDept({
        pageNum: 1,
        pageSize: 500
      }).then(response => {
        this.deptOptions = this.handleTree(response.data, 'deptId')
      })
    },
    /** 酒店类型字典翻译 */
    hotelTypeFormat (val) {
      return this.selectDictLabel(this.hotelTypeOptions, val)
    },
    // 下一步
    onNext () {
      this.current++
    },
    // 上一步
    onPrev () {
      this.current--
    },
    // 取消按钮
    onClose () {
      this.$refs.form.resetFields()
      this.open = false
      this.reset()
    },
    // 确认按钮
    onOk () {
      if (this.current === 0) {
        this.$refs.form.validate(valid => {
          if (valid) {
            this.current++
          }
        })
        return
      }
      if (this.current === 1) {
        this.$refs.form.validate(valid => {
          if (valid) {
            // websocket 连接
            this.$refs.webSocket.join()
          }
        })
        return
      }
      if (this.current === 2) {
        this.okText = '完成'
        this.current++
        return
      }
      if (this.current === this.steps.length - 1) {
        this.open = false
        this.$emit('ok')
      }
    },
    // 表单重置
    reset () {
      this.layoutShow = false
      this.form = {
        caseId: undefined,
        userId: undefined,
        deptId: undefined,
        caseName: undefined,
        caseDescribe: undefined,
        caseType: undefined,
        initAmount: undefined,
        electricity: undefined,
        water: undefined,
        round: undefined,
        remark: undefined,
        layoutModel: 'recommended',
        personnelModel: 'recommended',
        deptIds: [],
        depts: [],
        postIds: []
      }
    },
    /** 获取布局类型 */
    getLayoutList () {
      const layoutQueryParam = {
        pageNum: 1,
        pageSize: 10
      }
      listLayout(layoutQueryParam).then(response => {
        this.layoutOptions = response.rows
      })
    },
    /** 新增按钮操作 */
    handleAdd (row) {
      this.current = 0
      this.okText = '下一步'
      this.buttonState = false
      this.reset()
      this.open = true
      this.formTitle = '添加案例'
      this.progress = 0
      this.progressMsg = '数据执行中...'
      this.progressStatus = 'normal'
      this.form.deptIds = []
      this.form.postIds = []
      this.deptShow = false
      this.postShow = false
    },
    /** 修改按钮操作 */
    handleUpdate (row, ids) {
      this.current = 0
      this.okText = '下一步'
      this.buttonState = false
      this.reset()
      const caseId = row ? row.caseId : ids
      getCase(caseId).then(response => {
        this.form = response.data
        this.open = true
        this.formTitle = '修改案例'
        this.progress = 0
        this.progressMsg = '数据执行中...'
        this.progressStatus = 'normal'
        this.form.deptIds = []
        this.form.postIds = []
        this.deptShow = false
        this.postShow = false
      })
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.caseId !== undefined && this.form.caseId !== null) {
            updateCase(this.form).then()
          } else {
            addCase(this.form).then()
          }
        } else {
          return false
        }
      })
    },
    /** websocket 关闭 */
    webSocketClose (data) {
      this.progressMsg = data.msg
      this.buttonState = false
    },
    /** webSocket 执行错误 */
    webSocketError (data) {
      this.resultShow = false
      this.current++
    },
    /** webSocket 消息推送 */
    webSocketMessage (data) {
      console.log(data)
      this.progress = data.progress
      this.progressMsg = data.msg
    },
    /** webSocket 连接成功 */
    webSocketSuccess () {
      this.buttonState = true
      this.submitForm()
      this.current++
    },
    // 布局模式
    handleLayoutModel (value) {
      if (value === 'optional') {
        this.layoutShow = true
      } else {
        this.form.layoutIds = []
        this.layoutShow = false
      }
    },
    // 人员模式
    handlePersonnelModel (value) {
      if (value === 'optional') {
        this.deptShow = true
      } else {
        this.form.deptIds = []
        this.form.postIds = []
        this.deptShow = false
        this.postShow = false
      }
    },
    /** 部门设置改变事件 */
    deptChange (value, label, extra) {
      console.log(value)
      this.deptGroupList = value
      const idList = []
      value.forEach(item => {
        idList.push(item.value)
      })
      console.log(idList)
      this.form.deptIds = idList
      if (idList.length > 0) {
        // 根据选中的部门动态查询对应的岗位
        listPostByDeptIds(idList).then(response => {
          this.postOptions = response.data
          if (this.postOptions.length > 0) {
            this.postShow = true
          }
        })
      } else {
        this.form.postIds = []
        this.postShow = false
      }
    }
  }
}
</script>

<style scoped>
.steps-content {
  margin-top: 20px;
  min-height: 300px;
}
</style>
